package AnsatzTilo;
import javax.swing.SwingUtilities;


public class Main {
	
	private EventChain chain;
	private Clock clock;
	private Reporter reporter;
	private long terminationTime = 10000;
	private long sleep = 1;

	public Main() {
		initializeComponents();
		manageEventChain();
		waitForTermination();
	}

	private void waitForTermination() {
		while(true){
			if(clock.isTerminated()){
				//chain.stop();
				//clock.stop();
				finalizeReport();
				System.exit(0);
			}
			clock.tick();
		}
	}
	
	public void finalizeReport() {
		reporter.addEntry("\n");
		reporter.addEntry("Queu Minimum: " + 0);
		reporter.addEntry("Queu Maximum: " + reporter.getMax());
		reporter.addEntry("Arrivals: " + reporter.getArrivals());
		reporter.addEntry("Completions: " + reporter.getCompletions());
		reporter.addEntry("Actual Stack: " + reporter.getStack());
		reporter.printHistory();
	}

	private void manageEventChain() {
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.arriveEvent(new ArrivalEvent());
		chain.completeEvent(new CompletionEvent());
		chain.completeEvent(new CompletionEvent());
		chain.completeEvent(new CompletionEvent());
		chain.completeEvent(new CompletionEvent());
		
		chain.completeEvent(new CompletionEvent());
		chain.completeEvent(new CompletionEvent());
	}

	private void initializeComponents() {
		initializeClock();
		initializeReporter();
		initializeEventChain();
	}

	private void initializeReporter() {
		this.reporter = new Reporter();
		reporter.addEntry("Time - Stack - Arrival - Completion \n 0  -  0  -    -   ");
	}

	private void initializeEventChain() {
		chain = new EventChain(reporter, clock);
		chain.start();
	}

	public void initializeClock(){
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				clock = new Clock(sleep, terminationTime);
				clock.start();
			}
		});		
		while(clock == null);
	}
	
	public void setReporter(Reporter reporter){
		this.reporter = reporter;
	}

	public static void main(String[] args) {
		new Main();	
	}
	
	public Clock getClock(){
		return this.clock;
	}
	

}
